package com.example.springbootdemo.bean.core;

import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolManager {
    private static ThreadPoolManager instance;
    private ThreadPoolExecutor executor;

    private ThreadPoolManager() {
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = corePoolSize * 2;
        long keepAliveTime = 3000L;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();

        executor = new ThreadPoolExecutor(
                corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
    }

    public static synchronized ThreadPoolManager getInstance() {
        if (instance == null) {
            instance = new ThreadPoolManager();
        }
        return instance;
    }

    public <T> List<Future<T>> submitTasks(List<Callable<T>> tasks) throws InterruptedException {
        return executor.invokeAll(tasks);
    }

    public void shutdown() {
        executor.shutdown();
    }
}
